import { ssoLogin, login, getUserCheckPwd } from '@/api/api.js'
import router from '@/router/index'
import { ElMessage, ElMessageBox } from 'element-plus'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useRouterStore } from './router'
import { dictStore } from './dict'
import { sessionMemory } from '@/utils/sessionMemory'
import { getSysparamFileServer } from '@/api/system'
import route from './path'
import { appCurrentState } from '@/pinia/modules/app'
export const useUserStore = defineStore('user', () => {

  const baseConfig = ref({ sideMode: 'dark' })
  // 退出登录 需要清除
  const isTopMenus = ref(window.sessionStorage.getItem('isTopMenus') || 1)
  const userInfo = ref(sessionMemory.getItem('userInfo'))
  const orgInfo = ref(sessionMemory.getItem('orgInfo')) // level 1省级 2市级 3区县 4乡镇街道
  const roleInfo = ref(sessionMemory.getItem('roleInfo'))
  const token = ref(sessionMemory.getItem('token'))
  const userAreaArr = ref(sessionMemory.getItem('userAreaArr'))
  const userLastArea = ref(sessionMemory.getItem('userLastArea'))
  const fileUrl = ref(sessionMemory.getItem('fileUrl'))



  // 存储token
  const setToken = (val) => {
    token.value = val
    sessionMemory.setItem("token", token.value)
  }
  // 存储用户信息
  const setUser = (val) => {
    sessionMemory.setItem("userInfo", val)
    userInfo.value = val
  }
  // 改变org
  const changeOrgStatus = val => {
    let org = sessionMemory.getItem('orgInfo')
    orgInfo.value = ""
    org.isApproveSubmit = val
    orgInfo.value = org
    sessionMemory.setItem("orgInfo", org)
  }
  // 存储用户所属机构信息
  const setOrg = (val) => {
    sessionMemory.setItem("orgInfo", val) 
    orgInfo.value = val
    // 存储用户区划
    let userAreaArrKey = ['provinceCode', 'cityCode', 'countyCode', 'streetCode', 'communityCode']
    let areaArr = []
    userAreaArrKey.forEach(item => {
      val[item] && areaArr.push(val[item])
    })
    userAreaArr.value = areaArr
    let arr = areaArr.filter(item => item)
    userLastArea.value = arr[arr.length - 1]
    sessionMemory.setItem('userAreaArr', areaArr)
    sessionMemory.setItem('userLastArea', arr[arr.length - 1])
  }

  // 存储用户所属角色信息
  const setRole = (val) => {
    roleInfo.value = val
    sessionMemory.setItem("roleInfo", val)
  }

  const setFileUrl = async () => {
    const res = await getSysparamFileServer()
    fileUrl.value = location.origin + '/api' + res.data.fileServer
    sessionMemory.setItem("fileUrl", fileUrl.value)
  }

  /* 登录 */
  const LoginIn = async (loginInfo) => {
    try {
      const result = await login(loginInfo)
      if (result.succeed) {
        //存储密钥（加密）
        setToken(result.data.accessToken)
        // 存储用户信息
        setUser(result.data.user)
        setOrg(result.data.org)
        setRole(result.data.roleList)
        // 存储fileUrl
        await setFileUrl()
        // 存储字典
        await dictStore().getDict()
        // 获取后台路由-存储路由
        await useRouterStore().SetAsyncRouter()
        let asyncRouters = useRouterStore().asyncRouters
        asyncRouters.allRoutes.forEach(asyncRouter => {
          router.addRoute(asyncRouter)
        })
        return { ...result, asyncRouters }
      } else {
        router.push('/login')
      }
    } catch (e) {
      console.log(e);
      router.push('/login')
    }
  }

  const ssoLoginIn = async (loginInfo) => {
    try {
      const result = await ssoLogin(loginInfo)
      if (result.succeed) {
        //存储密钥（加密）
        setToken(result.data.accessToken)
        // 存储用户信息
        setUser(result.data.user)
        setOrg(result.data.org)
        setRole(result.data.roleList)
        // 存储fileUrl
        await setFileUrl()
        // 存储字典
        await dictStore().getDict()
        // 获取后台路由-存储路由
        await useRouterStore().SetAsyncRouter()
        let asyncRouters = useRouterStore().asyncRouters
        asyncRouters.allRoutes.forEach(asyncRouter => {
          router.addRoute(asyncRouter)
        })
        // return {...result,asyncRouters}
        // 判断是否显示顶部菜单
        if (result.data.user.enterIndex == 1) {
          // 有顶部菜单
          sessionMemory.setItem('isTopMenus', 1)
          isTopMenus.value = 1
          await getDefaultMenu(asyncRouters.leftRoutes, loginInfo)
        } else {
          // 无顶部菜单
          sessionMemory.setItem('isTopMenus', 2)
          isTopMenus.value = 2
          await getDefaultMenu(asyncRouters.allRoutes, loginInfo)
        }
        return true
      } else {
        router.push('/login')
      }
    } catch (e) {
      router.push('/login')
      console.log(e);
    }
  }

  const getTargetMenu = async (loginInfo)=>{
    // if(loginInfo.type == route[loginInfo.type]) {
    // }
    appCurrentState().SET_SSOLOGIN_INFOS(loginInfo)
    await router.push(route[loginInfo.type].path)
  }

  const getDefaultMenu = async (routes, loginInfo) => {
    if (loginInfo && loginInfo.type) {
      getTargetMenu(loginInfo)
    } else {
      if (routes?.length > 0) {
        if (routes[0].children?.length === 0) {
          // await router.push(routes[0].path)
          await router.push('/home')
        } else {
          // 递归找到默认菜单
          getDefaultMenu(routes[0].children,loginInfo)
        }
      }
    }
  }
  /* 清理数据 */
  const ClearStorage = () => {
    sessionStorage.clear()
    // pinia数据清空
    isTopMenus.value = 1
    userInfo.value = ""
    orgInfo.value = ""
    roleInfo.value = ""
    token.value = ""
    userAreaArr.value = ""
    userLastArea.value = ""
    fileUrl.value = ""
    dictStore().clearDict()

  }
  /* 登出*/
  const LoginOut = () => {
    ClearStorage()
    router.push({ name: 'Login', replace: true })
  }



  /* 设置侧边栏模式*/
  const changeSideMode = async (data) => {
    baseConfig.value.sideMode = data
    ElMessage({
      type: 'success',
      message: '设置成功'
    })
  }

  const mode = computed(() => baseConfig.value.sideMode)
  const sideMode = computed(() => {
    if (baseConfig.value.sideMode === 'dark') {
      return 'dark'
    } else {
      return "light"
    }
  })
  const baseColor = computed(() => {
    if (baseConfig.value.sideMode === 'dark') {
      return '#fff'
    } else {
      return '#191a23'
    }
  })
  const activeColor = computed(() => {
    if (baseConfig.value.sideMode === 'dark' || baseConfig.value.sideMode === 'light') {
      return '#4D70FF'
    }
    return '#4D70FF'
  })



  return {
    fileUrl,
    userInfo,
    userLastArea,
    userAreaArr,
    orgInfo,
    roleInfo,
    isTopMenus,
    token,
    LoginIn,
    ssoLoginIn,
    LoginOut,
    changeSideMode,
    mode,
    sideMode,
    setToken,
    baseColor,
    activeColor,
    ClearStorage,
    changeOrgStatus,
    getDefaultMenu
  }
})
